﻿Imports System.IO
Partial Class WebForm_ManageWorkContent_SearchPlanHeader
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Me.BindDDLOrganization()
        End If
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(Me.gv)

        '只有管理人員才可以按次年例行服務計劃之產生
        If MyObj.IsSystem(clsAuth.GetUserID()) = False Then
            Me.btnAddNextPlan.Visible = False
        Else
            Me.btnAddNextPlan.Visible = True
        End If
    End Sub

    Protected Sub btnQuery_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnQuery.Click
        Me.BindGV()
    End Sub

    Protected Sub btnAddPlanItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddPlanItem.Click
        RaiseEvent Add(Me, New EventArgs)
    End Sub


    Public Sub BindGV()
        Dim dat As New clsData
        Dim sql As New MyOrganizationDataFilter(True)

        sql.Length = 0

        sql.AppendFormat(" select a.*, a.OrganizationID as UOrganizationID ,b.OrganizationName,(a.Year-1911) as tYear from ")
        sql.AppendFormat(" CleanPlanHeader a inner join OrganizationView b  ")
        sql.AppendFormat(" on a.OrganizationID = b.UOrganizationID ")
        sql.AppendFormat(" Where 1 = 1 ")

        If Me.AnnualControl1.Anaual <> "" Then
            sql.AppendFormat(" And a.Year=@Year ")
            sql.AddWithValue("Year", Me.AnnualControl1.Anaual)
        End If

        If Me.ddlOrganization.SelectedValue <> "" Then
            sql.AppendFormat(" And a.OrganizationID=@OrganizationID ")
            sql.AddWithValue("OrganizationID", Me.ddlOrganization.SelectedValue)
        End If

        sql.AppendFormat(" Order By A.Year ")

        Me.gv.DataSource = dat.GetData(sql)
        Me.gv.DataBind()

    End Sub

    Protected Sub gv_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gv.PageIndexChanging
        Me.gv.PageIndex = e.NewPageIndex
        Me.BindGV()
    End Sub

    Protected Sub gv_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv.RowCommand
        If e.CommandName = "MyEdit" Then
            Me.PlanHeaderID = e.CommandArgument.ToString()
            RaiseEvent Editing(Me, New EventArgs)
        ElseIf e.CommandName = "MyDownload" Then

            Dim dat As New clsData
            Dim sql As New MyStringBuilder

            sql.Length = 0

            sql.AppendFormat(" Select * From CleanPlanHeader ")
            sql.AppendFormat(" Where PlanHeaderID=@PlanHeaderID ")

            sql.AddWithValue("PlanHeaderID", e.CommandArgument.ToString())

            Dim dt As System.Data.DataTable = dat.GetData(sql)

            If dt.Rows.Count > 0 Then
                Dim FileInfo As New System.IO.FileInfo(Server.MapPath(dt.Rows(0)("FileUrl").ToString()))
                Me.Response.Clear()
                Me.Response.AddHeader("Content-Disposition", ("attachment;filename=" & Server.UrlPathEncode(dt.Rows(0)("FileName").ToString())))
                Me.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8")
                Me.Response.AddHeader("Content-Length", FileInfo.Length.ToString())
                Me.Response.ContentType = "application/octet-stream"
                Me.Response.WriteFile(FileInfo.FullName)

                Me.Response.End()
            Else
                MyObj.ShowMessage("此計劃尚未上傳檔案")
            End If


        End If
    End Sub

    Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim haveAccess As New MyBoolean

            haveAccess.Add(Not TypeOf DataBinder.Eval(e.Row.DataItem, "HaveAccess") Is DBNull AndAlso DataBinder.Eval(e.Row.DataItem, "HaveAccess") = "Y")
            '編輯按鈕權限
            If haveAccess.Value = True Then
                TryCast(e.Row.FindControl("lknEdit"), LinkButton).Visible = True
            Else
                TryCast(e.Row.FindControl("lknEdit"), LinkButton).Visible = False
            End If
            'If clsAuth.IsAdministrator() Then
            '    TryCast(e.Row.FindControl("lknEdit"), LinkButton).Visible = True
            'Else
            '    Dim uOrgID As String = CType(e.Row.FindControl("lblUOrganizationID"), Label).Text

            '    If uOrgID = clsAuth.GetUser().UOrganizationID Then

            '        'TryCast(e.Row.FindControl("mvForm"), MultiView).SetActiveView(TryCast(e.Row.FindControl("vwEdit"), View))
            '    Else

            '        'TryCast(e.Row.FindControl("mvForm"), MultiView).SetActiveView(TryCast(e.Row.FindControl("vwSelect"), View))
            '    End If
            'End If

        End If
    End Sub
    Protected Function GetServiceData(ByVal year As Integer, ByVal UOrganizationID As String) As Data.DataTable
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.Length = 0

        sql.AppendFormat("Select * from CleanPlan where year(StartDate)='{0}' ", year)

        If UOrganizationID <> "" Then
            sql.AppendFormat("and UOrganizationID='{0}' ", UOrganizationID)
        Else
            sql.AppendFormat("and UOrganizationID not in (select UOrganizationID from CleanPlan where year(StartDate)='{0}') ", year + 1)
        End If

        Return dat.GetData(sql)
    End Function
    Protected Function GetYearPlan(ByVal Year As Integer, ByVal OrganizationID As String) As Data.DataTable
        Dim sql As New MyStringBuilder
        Dim dat As New clsData

        sql.Length = 0
        sql.AppendFormat(" Select * From CleanPlanHeader ")
        sql.AppendFormat(" Where Year = '{0}' ", Year)
        If OrganizationID <> "" Then
            sql.AppendFormat("and OrganizationID='{0}' ", OrganizationID)
        Else
            sql.AppendFormat("and OrganizationID not in (select OrganizationID from CleanPlanHeader where [Year]='{0}' ) ", Year + 1)
        End If
        Return dat.GetData(sql)
    End Function
    Protected Sub btnAddNextPlan_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddNextPlan.Click
        Dim sql As New MyStringBuilder
        Dim dat As New clsData
        Dim filedt As Data.DataTable
        Dim ServiceDT As Data.DataTable
        ' Dim ServiceNextDT As Data.DataTable

        Dim PlanID As String = ""
        Dim NowYear As Integer = Int32.Parse(AnnualControl1.Anaual)
        Dim FileOldUrl As String = ""
        Dim FileNewUrl As String = ""
        Dim IsCleanPlanHeader As Boolean = False
        '先判斷計畫是否已經產生
        If ddlOrganization.SelectedValue <> "" Then
            If GetYearPlan(NowYear + 1, ddlOrganization.SelectedValue).Rows.Count > 0 Then
                'MyObj.ShowMessage(String.Format("{0}的{1}年度計畫已經產生", ddlOrganization.SelectedItem.Text, NowYear - 1911 + 1))
                '    Exit Sub
                IsCleanPlanHeader = True
            End If
        Else
            If GetYearPlan(NowYear + 1, ddlOrganization.SelectedValue).Rows.Count = 0 Then
                'MyObj.ShowMessage(String.Format("{0}年度計畫已經產生", NowYear - 1911 + 1))
                'Exit Sub
                IsCleanPlanHeader = True
            End If

        End If

        '準備服務計畫資料

        filedt = GetYearPlan(NowYear, ddlOrganization.SelectedValue)

      


        '如果計畫不存在,才批次新增
        If IsCleanPlanHeader = False Then

            sql.Length = 0
            For i As Integer = 0 To filedt.Rows.Count - 1
                FileOldUrl = filedt.Rows(i)("FileUrl").ToString()
                FileNewUrl = "~/Downloads/ClanPlanHeader/" + Guid.NewGuid().ToString() + DateTime.Today.ToString("yyyyMMdd") + "." + FileOldUrl.Split(".")(1)
                '複製檔案
                Try
                    If File.Exists(Server.MapPath(FileOldUrl)) Then
                        File.Copy(Server.MapPath(FileOldUrl), Server.MapPath(FileNewUrl), False)
                    Else
                        File.Create(Server.MapPath(FileNewUrl))
                    End If
                Catch ex As Exception
                    MyObj.ShowMessage("複製檔案產生錯誤!")
                    Exit Sub
                End Try


                sql.AppendFormat("Insert Into CleanPlanHeader([Year],OrganizationID,PersonInCharge,[Subject],[FileName],FileUrl,CreateBy,CreateDate,UpdateBy,UpdateDate) ")
                sql.AppendFormat(" select ")
                sql.AppendFormat("'{0}', ", Int32.Parse(filedt.Rows(i)("Year").ToString()) + 1)
                sql.AppendFormat("'{0}', ", filedt.Rows(i)("OrganizationID").ToString())
                sql.AppendFormat("'{0}', ", filedt.Rows(i)("PersonInCharge").ToString())
                sql.AppendFormat("'{0}', ", "")
                sql.AppendFormat("'{0}', ", Int32.Parse(filedt.Rows(i)("Year").ToString()) + 1 - 1911 & "年_" & filedt.Rows(i)("FileName").ToString())
                sql.AppendFormat("'{0}', ", FileNewUrl)
                sql.AppendFormat("'{0}', ", clsAuth.GetUserID())
                sql.AppendFormat("{0}, ", "getdate()")
                sql.AppendFormat("'{0}', ", clsAuth.GetUserID())
                sql.AppendFormat("{0} where not exists (select * from CleanPlanHeader where [Year]='{1}' and OrganizationID='{2}'); ", "getdate()", Int32.Parse(filedt.Rows(i)("Year").ToString()) + 1, filedt.Rows(i)("OrganizationID").ToString())
            Next
            Try
                ' MyObj.WriteLog(sql.ToString())
                dat.AccData(sql)
            Catch ex As Exception
                MyObj.ShowMessage(ex.Message)
                Exit Sub
            End Try
        End If

        '準備服務項目的資料

        ServiceDT = Me.GetServiceData(NowYear, ddlOrganization.SelectedValue)
        Using scope As New Transactions.TransactionScope

            For j As Integer = 0 To ServiceDT.Rows.Count - 1
                sql.Length = 0
                sql.AppendFormat("insert CleanPlan (PlanHeaderID,ItemType,PlanName,UOrganizationID,OrganizationTel,Location,RegionType,PersonInCharge ")
                sql.AppendFormat(",StartDate,EndDate,IsPublic,CreateDate,CreateBy) Select ")
                sql.AppendFormat("(Select PlanHeaderID From CleanPlanHeader Where Year='{0}' ", NowYear + 1)
                sql.AppendFormat("and OrganizationID='{0}') ", ServiceDT.Rows(j)("UOrganizationID").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("ItemType").ToString())
                sql.AppendFormat(",'{0}' ", NowYear + 1 - 1911 & "年_" & ServiceDT.Rows(j)("PlanName").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("UOrganizationID").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("OrganizationTel").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("Location").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("RegionType").ToString())
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("PersonInCharge").ToString())
                sql.AppendFormat(",'{0:yyyy/MM/dd}' ", DateTime.Parse(ServiceDT.Rows(j)("StartDate").ToString()).AddYears(1))
                sql.AppendFormat(",'{0:yyyy/MM/dd}' ", DateTime.Parse(ServiceDT.Rows(j)("EndDate").ToString()).AddYears(1))
                sql.AppendFormat(",'{0}' ", ServiceDT.Rows(j)("IsPublic").ToString())
                sql.AppendFormat(",{0} ", "getdate()")
                sql.AppendFormat(",'{0}'; ", clsAuth.GetUserID())
                Try
                    '  MyObj.WriteLog(sql.ToString())
                    dat.AccData(sql)
                Catch ex As Exception
                    MyObj.ShowMessage(ex.Message)
                    Exit Sub
                End Try



                PlanID = MyObj.GetIdentity()
                sql.Length = 0
                sql.AppendFormat(" Insert Into CleanPlanContent(PlanID,ItemGroup,ItemValue)  Select ")
                sql.AppendFormat(" {0} ", PlanID)
                sql.AppendFormat(" ,c.ItemGroup ")
                sql.AppendFormat(" ,c.ItemValue ")
                sql.AppendFormat("From CleanPlanContent c ")
                sql.AppendFormat("Where c.PlanID ={0};  ", ServiceDT.Rows(j)("PlanID").ToString())


                Try
                    ' MyObj.WriteLog(sql.ToString())
                    dat.AccData(sql)
                    If IsCleanPlanHeader = False Then
                        MyObj.ShowMessage(String.Format("{0}年度{1}服務計劃及服務項目批次產生成功!", NowYear - 1911 + 1, ddlOrganization.SelectedItem.Text))
                    Else
                        MyObj.ShowMessage(String.Format("{0}年度{1}服務項目批次產生成功!", NowYear - 1911 + 1, ddlOrganization.SelectedItem.Text))
                    End If
                Catch ex As Exception
                    MyObj.ShowMessage(ex.Message)
                    Exit Sub
                End Try



            Next
            scope.Complete()
        End Using





    End Sub

End Class

Partial Class WebForm_ManageWorkContent_SearchPlanHeader

#Region "事件"
    Public Event Add(ByVal source As Object, ByVal e As EventArgs)
    Public Event Editing(ByVal source As Object, ByVal e As EventArgs)
#End Region

#Region "繫結資料"
    Private Sub BindDDLOrganization()
        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        sql.AppendFormat("select o.* ")
        sql.AppendFormat("from OrganizationView o ")
        sql.AppendFormat("where OrganizationName like '%公所%' and Active = 'Y' ")

        Me.ddlOrganization.DataTextField = "OrganizationName"
        Me.ddlOrganization.DataValueField = "UOrganizationID"
        Me.ddlOrganization.DataSource = MyObj.GetDDLDirectOrganizationData()
        Me.ddlOrganization.DataBind()

        If Me.ddlOrganization.Items.Count > 1 Then
            Me.ddlOrganization.Items.Insert(0, MyObj.GetDDLSelectAllItem())
        End If

    End Sub
#End Region

#Region "屬性"
    Public Property PlanHeaderID() As String
        Get
            Return ViewState("SelectedPlanHeaderID")
        End Get
        Set(ByVal value As String)
            ViewState("SelectedPlanHeaderID") = value
        End Set
    End Property
#End Region


End Class
